package com.hqyj.web.listener;

import com.hqyj.pojo.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;


/**
 * @author cz
 * 2021/8/16 15:19
 *
 *  统计网站在线人数
 *      session记录数据
 */
@WebListener
public class UserOnlineListener implements HttpSessionAttributeListener, ServletContextListener, HttpSessionListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        ServletContext context = session.getServletContext();
        int count = (int)context.getAttribute("count");
        context.setAttribute("count",count+1);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        ServletContext servletContext = session.getServletContext();
        int count = (int)servletContext.getAttribute("count");
        servletContext.setAttribute("count",count-1);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //在context中设置count，用来统计人数，初始值为0
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("count",0);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null){
            session.removeAttribute("user");
        }
    }
}
